<template>
  <div class="top-right-btn">
    <el-button circle size="mini" icon="el-icon-search" @click="toggleSearch()" />
    <el-button circle size="mini" icon="el-icon-refresh" @click="refresh()" />
    <el-popover placement="bottom-end" width="150" trigger="click" style="padding:7px;">
      <el-button slot="reference" circle size="mini" icon="el-icon-s-grid" />
      <el-checkbox
        v-model="allColumnsSelected"
        :indeterminate="allColumnsSelectedIndeterminate"
        @change="handleCheckAllChange"
      >
        全选
      </el-checkbox>
      <el-checkbox
        v-for="item in tableData"
        :key="item.label"
        v-model="item.visible"
        @change="handleCheckedTableColumnsChange(item)"
      >
        {{ item.label }}
      </el-checkbox>
    </el-popover>
  </div>
</template>
<script>
export default {
  name: 'Rightbar',
  props: {
    showSearch: {
      type: Boolean,
      default: true
    },
    tableData: {
      type: Array,
      default: function() { return [] }
    }
  },
  data() {
    return {

      tables: [],
      allColumnsSelected: true,
      allColumnsSelectedIndeterminate: false
    }
  },
  created() {

  },

  methods: {
    // 搜索
    toggleSearch() {
      this.$emit('update:showSearch', !this.showSearch)
    },
    // 刷新
    refresh() {
      this.$emit('queryTable')
    },
    // 全选
    handleCheckAllChange(val) {
      if (val === false) {
        this.allColumnsSelected = true
        return
      }
      for (const key in this.tableData) {
        this.tableData[key].visible = val
      }
      this.allColumnsSelected = val
      this.allColumnsSelectedIndeterminate = false
    },
    // 单选
    handleCheckedTableColumnsChange(item) {
      let totalCount = 0
      let selectedCount = 0
      for (const key in this.tableData) {
        ++totalCount
        selectedCount += this.tableData[key].visible ? 1 : 0
      }
      if (selectedCount === 0) {
        this.$message.info('请至少选择一列!')
        this.$nextTick(function() {
          item.visible = true
        })
        return
      }
      this.allColumnsSelected = selectedCount === totalCount
      this.allColumnsSelectedIndeterminate = selectedCount !== totalCount && selectedCount !== 0
    }
  }
}
</script>
<style>
.crud-opts-right {
    margin-left: auto;
  }
</style>
